package com.didispace.chapter56.controller;

import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.didispace.chapter56.domain.User;
import com.didispace.chapter56.service.UserService;
import com.didispace.chapter56.utils.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/datagoUser")
public class UserController {

    private RedisTemplate<String, String> redisTemplate;

    private UserService userService;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public RestResult<User> login(@RequestBody User datagoUser, HttpServletRequest request) {
        try {
            if (log.isDebugEnabled()) {
                log.debug("开始登录");
            }
            byte[] key = "c494ffdade8cfb269912868133a8586a".getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
            String kl = aes.encryptHex(datagoUser.getPassword());
            log.info("加密后的密码：{}", kl);
            datagoUser.setPassword(kl);
            datagoUser = userService.login(datagoUser.getName(), datagoUser.getPassword());
            if (!Objects.isNull(datagoUser)) {
                datagoUser.setLastLoginTime(new Date());
                datagoUser.setLastLoginIp(request.getRemoteAddr());
                datagoUser.setSessionId(request.getSession().getId());
                this.userService.update(datagoUser);
                //主要核心代码
                request.getSession().setAttribute("user", datagoUser.getId());
                redisTemplate.opsForValue().set(String.valueOf(datagoUser.getId()), request.getSession().getId());
                return RestResult.success(datagoUser);
            } else {
                return RestResult.failed("用户信息不存在,请联系管理员！！！");
            }
        } catch (Exception e) {
            log.error("登录出现错误", e);
        } finally {
            if (log.isDebugEnabled()) {
                log.debug("结束登录");
            }
        }
        return RestResult.failed("用户信息不存在,请联系管理员！！！");
    }
}
